package com.dubious.interview.graph;

public class GraphByMatrix {
    
    int[][] edges;
    
    public GraphByMatrix(int numVertices)
    {
        edges = new int[numVertices][numVertices];
    }
    
    public GraphByMatrix withEdge(int vertexA, int vertexB, int weight)
    {
        if(vertexA > edges.length)
        {
            throw new RuntimeException("VertexA index out of bounds: " + vertexA);
        } else if(vertexB > edges.length)
        {
            throw new RuntimeException("VertexB index out of bounds: " + vertexB);
        }
        
        edges[vertexA][vertexB] = weight;
        
        return this;
    }
    
    int[][] getEdges()
    {
        return edges;
    }
    
    @Override
    public boolean equals(Object otherObject)
    {
        if(otherObject == null || !(otherObject instanceof GraphByMatrix))
        {
            return false;
        }
        
        GraphByMatrix other = (GraphByMatrix) otherObject;
        
        if(other.edges.length != this.edges.length)
        {
            return false;
        }
        
        for(int i = 0; i < other.edges.length; i++)
        {
            for(int j = 0; j < other.edges.length; j++)
            {
                if(other.edges[i][j] != this.edges[i][j])
                {
                    return false;
                }
            }
        }
        
        return true;
    }
    
    @Override
    public int hashCode()
    {
        throw new UnsupportedOperationException("Not Yet Implemented");
    }
    
    @Override
    public String toString()
    {
        StringBuilder output = new StringBuilder();
        for(int i = 0; i < edges.length; i++)
        {
            for(int j = 0; j < edges.length; j++)
            {
                if(edges[i][j] != 0)
                {
                    output.append(
                            "(" + i 
                            + "," + j 
                            + "=" + edges[i][j]
                            + "),");
                }
            }
        }
        if(output.length() > 0)
        {
            output.deleteCharAt(output.length() - 1);
        }
        
        return output.toString();
    }
}
